<template>
  <div>
    <!-- 下拉选择框 -->
    <el-form  ref="queryForm" label-width="120px" style="margin-bottom: 20px;">
      <el-row>
        <el-col :span="6">
            <el-form-item label="日期"  style="width: 60%">
            <el-date-picker clearable
              v-model="searchDate"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="请选择日期">
            </el-date-picker>
          </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="选择参数">
            <el-select v-model="selectParams" placeholder="请选择参数">
              <el-option
                v-for="item in selectedYpInfoColumns"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>  
          </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="选择图形" prop="changeType" >
              <el-select v-model="changeType" placeholder="请选择需要图形" clearable>
              <el-option label="折线图" value="line"></el-option>
              <el-option label="柱状图" value="bar"></el-option>
              <el-option label="散点图" value="scatter"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          </el-col>
        </el-row>
      
    </el-form>

    

    <!-- 图表容器 -->
    <div>
      <span><h1><center>{{ searchDate }}秦皇岛海域{{ buoyName }}{{ selectParamsName }}{{changeTypeLabels[changeType]}}</center></h1></span>
    </div>
    <div id="seaPieLine" style="width: 100%; height: 400px;"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import resize from './mixins/resize'
import {getTabQIWEDataForTime,getTabQIYADataForTime,getTabSHDUDataForTime,getTabFGALDataForTime,getTabSHZHDataForTime,getTabBLOGDataForTime} from "@/api/seadata/sea";

export default {
  name: "seaPieLine",
  props: {
    buoyCoding: {
      type: String,
      default: "",
      required: true
    },
    buoyName: {
      type: String,
      default: "",
      required: true
    },
  },
  mixins: [resize],
  watch: {
  buoyCoding(newVal) {
    if (newVal) {
      this.getList(); // 当 buoyCoding 发生变化时重新获取数据
    }
    }
  },
  data() {
    return {
      chart: null,
      selectParamsName:"气温",
      selectParams: "airTemAvg",
      searchDate: this.parseTime(new Date(), '{y}-{m}-{d}'),
       //所有选项
       selectedYpInfoColumns: [
          { label: '气温', value: 'airTemAvg' },
          { label: '气压', value: 'pressureAvg' },
          { label: '湿度', value: 'humiAvg' },
          { label: '风速', value: 'tenMinWindSpdA' },
          { label: '风向', value: 'tenMinWindDirA' },
          { label: '水温', value: 'waterTem' },
          { label: '盐度', value: 'salinity' },
          { label: '叶绿素', value: 'yls' },
          { label: '最大波高', value: 'maxWaveHigh' },
          { label: '最大波向', value: 'waveDir' }
        ],
        xData: [],
        yData: [],
        changeType: "line",
        changeTypeLabels: {
          line: '折线图',
          bar: '柱状图',
          scatter: '散点图'
        }
    }
  },
  created() {
    this.getList();
  },
  mounted() {
    setTimeout(() => {
      this.initChart();
    }, 2000);
    // 设置每半小时(1800000毫秒)自动刷新数据1
    this.refreshTimer = setInterval(() => {
      this.getList();
    }, 1800000);
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
     // 清除定时器
     if (this.refreshTimer) {
      clearInterval(this.refreshTimer);
      this.refreshTimer = null;
    }
  },
  methods: {
    initChart() {
      this.chart = echarts.init(document.getElementById("seaPieLine"))
      this.chart.setOption({
        tooltip: {
          trigger: 'axis',
          position: function (pt) {
            return [pt[0], "10%"];
          }
        },
        title: {
          text: '24\n小\n时\n趋\n势\n图',   // 竖向排列的标题
          left: 50,             // 靠近 Y 轴左侧
          bottom: '40%',         // 垂直方向位置
          rotate: 0,             // 不旋转（每字换行）
          textAlign: 'center',   // 每个字居中对齐
          verticalAlign: 'middle',
        },   
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: Array.from({ length: 24 }, (_, i) => `${i.toString().padStart(2, '0')}:00`)
        },
        yAxis: {
          type: 'value',
        },
        series: [
          {
            name: this.selectParamsName,
            type: this.changeType,
            barWidth: 3,
            symbol: "none",
            sampling: "lttb",
            itemStyle: {
              color: "rgb(255, 70, 131)",
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: "rgb(255, 158, 68)",
                },
                {
                  offset: 1,
                  color: "rgb(255, 70, 131)",
                },
              ]),
            },
            data: this.yData,
          }
        ]
      })
    },
  getList() {
    console.log("this.buoyCoding",this.buoyCoding);
    const fullHours = Array.from({ length: 24 }, (_, i) =>
          `${i.toString().padStart(2, '0')}:00`
        );
    if(this.selectParams=='airTemAvg'){
      getTabQIWEDataForTime({searchDate:this.searchDate,buoyCoding:this.buoyCoding}).then((response) => {
        this.resultData = response.map(item => ({
            yData: item.airTemAvg,
            xData: item.hourOfDay
        }));
        this.yData = fullHours.map(hour => {
          const match = this.resultData.find(item => item.xData === hour);
          return match ? parseFloat(match.yData) : undefined; // 如果没有数据，返回 null
        });
        // 可选：更新图表数据
        this.updateChart();
     })
    }

    if(this.selectParams=='pressureAvg'){
      getTabQIYADataForTime({searchDate:this.searchDate,buoyCoding:this.buoyCoding}).then((response) => {
        this.resultData = response.map(item => ({
            yData: item.pressureAvg,
            xData: item.hourOfDay
        }));
        this.yData = fullHours.map(hour => {
          const match = this.resultData.find(item => item.xData === hour);
          return match ? parseFloat(match.yData) : undefined; // 如果没有数据，返回 null
        });
        // 可选：更新图表数据
        this.updateChart();
     })
    }


    if(this.selectParams=='humiAvg'){
      getTabSHDUDataForTime({searchDate:this.searchDate,buoyCoding:this.buoyCoding}).then((response) => {
        this.resultData = response.map(item => ({
            yData: item.humiAvg,
            xData: item.hourOfDay
        }));
        this.yData = fullHours.map(hour => {
          const match = this.resultData.find(item => item.xData === hour);
          return match ? parseFloat(match.yData) : undefined; // 如果没有数据，返回 null
        });
        // 可选：更新图表数据
        this.updateChart();
     })
    }


    if(this.selectParams=='tenMinWindSpdA'){
      getTabFGALDataForTime({searchDate:this.searchDate,buoyCoding:this.buoyCoding}).then((response) => {
        this.resultData = response.map(item => ({
            yData: item.tenMinWindSpdA,
            xData: item.hourOfDay
        }));
        this.yData = fullHours.map(hour => {
          const match = this.resultData.find(item => item.xData === hour);
          return match ? parseFloat(match.yData) : undefined; // 如果没有数据，返回 null
        });
        // 可选：更新图表数据
        this.updateChart();
     })
    }


    if(this.selectParams=='tenMinWindDirA'){
      getTabFGALDataForTime({searchDate:this.searchDate,buoyCoding:this.buoyCoding}).then((response) => {
        this.resultData = response.map(item => ({
            yData: item.tenMinWindDirA,
            xData: item.hourOfDay
        }));
        this.yData = fullHours.map(hour => {
          const match = this.resultData.find(item => item.xData === hour);
          return match ? parseFloat(match.yData) : undefined; // 如果没有数据，返回 null
        });
        // 可选：更新图表数据
        this.updateChart();
     })
    }


    if(this.selectParams=='waterTem'){
      getTabSHZHDataForTime({searchDate:this.searchDate,buoyCoding:this.buoyCoding}).then((response) => {
        this.resultData = response.map(item => ({
            yData: item.waterTem,
            xData: item.hourOfDay
        }));
        this.yData = fullHours.map(hour => {
          const match = this.resultData.find(item => item.xData === hour);
          return match ? parseFloat(match.yData) : undefined; // 如果没有数据，返回 null
        });
        // 可选：更新图表数据
        this.updateChart();
     })
    }


    if(this.selectParams=='salinity'){
      getTabSHZHDataForTime({searchDate:this.searchDate,buoyCoding:this.buoyCoding}).then((response) => {
        this.resultData = response.map(item => ({
            yData: item.salinity,
            xData: item.hourOfDay
        }));
        this.yData = fullHours.map(hour => {
          const match = this.resultData.find(item => item.xData === hour);
          return match ? parseFloat(match.yData) : undefined; // 如果没有数据，返回 null
        });
        // 可选：更新图表数据
        this.updateChart();
     })
    }


    if(this.selectParams=='yls'){
      getTabSHZHDataForTime({searchDate:this.searchDate,buoyCoding:this.buoyCoding}).then((response) => {
        this.resultData = response.map(item => ({
            yData: item.yls,
            xData: item.hourOfDay
        }));
        this.yData = fullHours.map(hour => {
          const match = this.resultData.find(item => item.xData === hour);
          return match ? parseFloat(match.yData) : undefined; // 如果没有数据，返回 null
        });
        // 可选：更新图表数据
        this.updateChart();
     })
    }


    if(this.selectParams=='maxWaveHigh'){
      getTabBLOGDataForTime({searchDate:this.searchDate,buoyCoding:this.buoyCoding}).then((response) => {
        this.resultData = response.map(item => ({
            yData: item.maxWaveHigh,
            xData: item.hourOfDay
        }));
        this.yData = fullHours.map(hour => {
          const match = this.resultData.find(item => item.xData === hour);
          return match ? parseFloat(match.yData) : undefined; // 如果没有数据，返回 null
        });
        // 可选：更新图表数据
        this.updateChart();
     })
    }

    if(this.selectParams=='waveDir'){
      getTabBLOGDataForTime({searchDate:this.searchDate,buoyCoding:this.buoyCoding}).then((response) => {
        this.resultData = response.map(item => ({
            yData: item.waveDir,
            xData: item.hourOfDay
        }));
        this.yData = fullHours.map(hour => {
          const match = this.resultData.find(item => item.xData === hour);
          return match ? parseFloat(match.yData) : undefined; // 如果没有数据，返回 null
        });
        // 可选：更新图表数据
        this.updateChart();
     })
    }
  },
  handleQuery() {                  
      this.selectParamsName = this.selectedYpInfoColumns.filter((f)=>f.value===this.selectParams)[0].label;                
      this.getList();
    },
    updateChart() {
      this.chart.setOption({
        series: [{
          type: this.changeType,
          data: this.yData,
          barWidth: 10,
          name: this.selectParamsName,
        }]
      });
  },
}
  }
</script>
